package com.example.service.impl;

import com.example.entity.Teacher;
import com.example.mapper.TeacherMapper;
import com.example.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanhang.common.util.PageResult;
import com.example.entity.School;
import com.example.service.ISchoolService;
import com.example.vo.TeacherVO;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {
    @Autowired
    private ISchoolService departmentService;
    // 1. 分页查询
    @Override
    public PageResult<Teacher> findByPage(Integer page, Integer pageSize) {
        // 1. 开始分页
        Page<Teacher> page1 = this.page(new Page<>(page, pageSize));

        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    // 3. 条件带分页查询
    @Override
    public PageResult<Teacher> search(Integer page, Integer pageSize, TeacherVO vo) {
        // 1. 进行分页带条件查询
        // 1.1 封装查询条件
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getSname()), "sname",  vo.getSname() )
                .like(StrUtil.isNotBlank(vo.getAddr()), "addr", vo.getAddr())
                .eq(vo.getScid() != null && vo.getScid() != 0, "sc_id", vo.getScid());
        // 1.2 开始分页查询
        Page<Teacher> page1 = this.page(new Page<>(page, pageSize), wrapper);
        // 1.3 处理学生所在班级名称
        page1.getRecords().forEach(st -> {
            School department = departmentService.getById(st.getScid());
            st.setScname(department.getScname());
        });
        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    // 添加学生
    @Override
    public boolean add(Teacher staff) {
        return this.save(staff);
    }
}
